package com.pm.common.security;

import com.pm.common.annotation.PassToken;
import com.pm.common.annotation.UserLoginToken;
import com.pm.common.exception.CommonException;
import com.pm.common.exception.ExpCodeState;
import com.pm.entity.po.security.User;
import com.pm.mapper.security.UserMapper;
import com.pm.utils.security.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截器，验证token Title: AuthenticationInterceptor
 *
 * @author WuJin
 * @date 2020年1月6日
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userDao;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 跨域访问设置
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, content-Type, Accept, Authorization,terminal");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        // 获取请求头的token
        String token = httpServletRequest.getHeader("Authorization");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Class<?> obj = handlerMethod.getBeanType();
        Method m = handlerMethod.getMethod();
        // 检查是否有passToken注释，有则跳过验证
        if (obj.isAnnotationPresent(PassToken.class) || m.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = obj.getAnnotation(PassToken.class);
            if (passToken == null) {
                passToken = m.getAnnotation(PassToken.class);
            }
            if (passToken.required()) {
                return true;
            }
        }
        // 检查是否有需要用户权限的注解
        if (obj.isAnnotationPresent(UserLoginToken.class) || m.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = obj.getAnnotation(UserLoginToken.class);
            if (userLoginToken == null) {
                userLoginToken = m.getAnnotation(UserLoginToken.class);
            }
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new CommonException(ExpCodeState.login_failed_for_token);
                } else {
                    token = token.substring(token.indexOf(" ") + 1, token.length());
                    // 获取token中的用户信息
                    Claims claims;
                    try {
                        claims = JwtTokenUtil.parseJWT(token);

                    } catch (ExpiredJwtException e) {
                        throw new CommonException(ExpCodeState.login_failed_for_token);
                    }
                    String email = claims.getId();
                    User user = userDao.loadUserInfoByUserName(email);
                    if (user == null) {
                        throw new CommonException(ExpCodeState.login_failed_user_nots);
                    }
                    httpServletRequest.setAttribute("CurrentUser", user);
                }
            }
        }
        return true;
    }

    // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    // 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }
}